package proyectoFC_2_3_3.koyicabuto;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import proyectoFC_2_3_3.koyicabuto.funciones.Funciones;
import proyectoFC_2_3_3.koyicabuto.funciones.FuncionesBaseDatos;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class NuevoEventoActivity extends MapActivity{
	
	private EditText nombreEvento;
	private MapView mapView = null;
    private ImageButton searchButton = null;
    private EditText searchText = null;
    private MapController mapController = null;
    private static Double latitud = null;
    private static Double longitud = null;
    private Long idGrupoSeleccionado = null;
    private EditText comentarioEvento = null;

	
	private FuncionesBaseDatos funcionesBaseDatos = new FuncionesBaseDatos();
	private Funciones funciones = new Funciones();
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nuevoevento);
        
        Bundle extras = getIntent().getExtras();
		if(extras != null){
			idGrupoSeleccionado = extras.getLong("idGrupoSeleccionado");
		}
        
        this.nombreEvento = (EditText)findViewById(R.id.Nombre);
        this.comentarioEvento = (EditText)findViewById(R.id.EditComentario);
        this.searchButton = (ImageButton)findViewById(R.id.searchButton);
        this.searchText = (EditText)findViewById(R.id.searchText);
        
        this.mapView = (MapView)findViewById(R.id.mapView);
        this.mapView.setBuiltInZoomControls(true);
        this.mapController = mapView.getController();

        searchButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	if(searchText.getText().length() > 0){
            		getLocationInfo(searchText.getText().toString());
            	   	GeoPoint geoPoint = new GeoPoint(latitud.intValue(), longitud.intValue());
	            	
	            	ocultarTecladoVirtual(mapView);
	            	
	            	Drawable drawable = view.getResources().getDrawable(R.drawable.target_map_selector);
	            	
	            	OverlayItem overlayitem = new OverlayItem(geoPoint, null, null);
	            	List<Overlay> mapOverlays = mapView.getOverlays();
	            	MyOverlay myOverlay = new MyOverlay(drawable, mapView.getContext());
	            	myOverlay.addOverlay(overlayitem);
	  		        mapOverlays.add(myOverlay);
	            	
	            	mapController.setCenter(geoPoint);
	                mapController.setZoom(16);
	
	                mapView.invalidate();
            	}
            }
        });
    }
	
	private static JSONObject getLocationInfo(String address) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
        	
        	//Eliminamos los espacios en blanco del inicio y final de la cadena
            address = address.trim();
        	
	        address = address.replaceAll(" ","%20");    
	        
	        HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false&region=es");
	        HttpClient client = new DefaultHttpClient();
	        HttpResponse response;
	        stringBuilder = new StringBuilder();

            response = client.execute(httppost);
            HttpEntity entity = response.getEntity();
            InputStream stream = entity.getContent();
            int b;
            while ((b = stream.read()) != -1) {
                stringBuilder.append((char) b);
            }
            
        } catch (ClientProtocolException e) {
        	e.printStackTrace();
        } catch (IOException e) {
        	e.printStackTrace();
        }

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject = new JSONObject(stringBuilder.toString());
            
        } catch (JSONException e) {
            e.printStackTrace();
        }
        
        try {

        	longitud = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
            					  .getJSONObject("geometry").getJSONObject("location")
            					  .getDouble("lng")*1E6;

            latitud = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
            				     .getJSONObject("geometry").getJSONObject("location")
            				     .getDouble("lat")*1E6;

        } catch (JSONException e) {
        	e.printStackTrace();
        }

        return jsonObject;
    }
	
	public void ocultarTecladoVirtual(View view){
		nombreEvento.clearFocus();
		searchText.clearFocus();
		
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
	}
	
	public void onClickBotonVolver(View view){		
		Intent i = new Intent(this, GrupoActivity.class);
		i.putExtra("tabSeleccionada", "tabEvento");
		i.putExtra("idGrupoSeleccionado", idGrupoSeleccionado);
		startActivity(i);
	}
	
	public void onClickBotonGuardar(View view){
		if(validaGuardarEvento()){
			boolean error = true;
			
			String comentario = null;
			if(comentarioEvento.getText() != null ){
				comentario = comentarioEvento.getText().toString();
			}
			
			SQLiteDatabase gruposDataBase = funcionesBaseDatos.conectaWritableBaseDeDatos(this); 		
			
			try{
				if(gruposDataBase != null){
					
					Double longitudAux = longitud/1E6;
					Double latitudAux = latitud/1E6;
					
					//Guardamos el Grupo
					gruposDataBase.execSQL("INSERT INTO EVENTOS (EV_NOMBRE, EV_LONGITUD, EV_LATITUD, EV_GR_ID, EV_DESCRIPCION) " +
										   "VALUES('" + nombreEvento.getText().toString() + "'," + longitudAux + "," + latitudAux + "," + idGrupoSeleccionado + 
										   ", '" + comentario + "' )") ;
					
					funcionesBaseDatos.cierraBaseDeDatos(gruposDataBase);
					error = false;
				}
				
			}catch (Exception e) {
				error = true;
				System.out.println("Excepcion al onClickBotonGuardar evento: " +e.getMessage());
			}
			if(!error){
				ocultarTecladoVirtual(view);
				Toast.makeText(this, "Evento: " + this.nombreEvento.getText().toString() + " almacenado correctamente.", Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	private boolean validaGuardarEvento(){
		boolean validado = false;
		if(nombreEvento.getText().length() <= 0 && searchText.getText().length() <= 0){
			funciones.crearDialogoAlerta("Error", "Debe introducir un nombre y seleccionar una ubicación.", this);
		}else if(nombreEvento.getText().length() > 0 && searchText.getText().length() <= 0){
			funciones.crearDialogoAlerta("Error", "Debe seleccionar una ubicación.", this);
		}else if(nombreEvento.getText().length() <= 0 && searchText.getText().length() > 0){
			funciones.crearDialogoAlerta("Error", "Debe introducir un nombre.", this);
		}else{
			validado = true;
		}
		return validado;
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
}
	